//
//  MonthReportViewController.m
//  MoneyLog
//
//  Created by Max on 11-6-12.
//  Copyright 2011年 wicresoft. All rights reserved.
//

#import "MonthReportViewController.h"
#import "ColumnChartViewController.h"
#import "RecordWrapper.h"
#import "MonthReportItem.h"
#import "ColumnChartItem.h"

extern NSString *kRowViewKey;
extern NSString *kRowItemKey;

@implementation MonthReportViewController
@synthesize _tableView;
@synthesize dataSourceArray;
@synthesize searchStartDate,searchEndDate;
@synthesize dateSelectView;
@synthesize startPickerView,endPickerView;
@synthesize pikcerDataSource;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [titleView removeFromSuperview];
    [titleButton release];
    
    [_tableView release];
    [dataSourceArray release];
    [searchStartDate release];
    [searchEndDate release];
    
    [dateSelectView release];
    [startPickerView release];
    [endPickerView release];
    [pikcerDataSource release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSString *titleString =[NSString stringWithFormat:@" %04d/%02d-%04d/%02d",searchStartDate.year,searchStartDate.month,searchEndDate.year,searchEndDate.month];
    titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];//allocate titleView
    titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleButton setFrame:CGRectMake(0, 0, 200, 38)];
    [titleButton addTarget:self action:@selector(titleAction) forControlEvents:UIControlEventTouchUpInside];
    [titleButton setTitle:titleString forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"group_button_down.png"] forState:UIControlStateNormal];
    titleButton.titleLabel.textColor = [UIColor whiteColor];
    titleButton.backgroundColor =[UIColor clearColor];
    [titleView addSubview:titleButton];
    self.navigationItem.titleView=titleView;
    
    UIBarButtonItem *chartButton = [[UIBarButtonItem alloc] 
                                    initWithTitle:@"柱图" 
                                    style:UIBarButtonItemStyleBordered 
                                    target:self
                                    action:@selector(chartAction)];
    self.navigationItem.rightBarButtonItem = chartButton;
    [chartButton release];
    
    dataSourceArray = [[NSMutableArray alloc] initWithCapacity:1];
    
    CGRect appRect = [[UIScreen mainScreen] applicationFrame];
    dateSelectView.frame = CGRectMake(0, appRect.size.height, appRect.size.width, 250);
    dateSelectView.hidden=YES;
    [self.view addSubview:dateSelectView];
    //[self.view insertSubview:dateSelectView aboveSubview:chartView];
    
    pikcerDataSource = [[NSMutableArray alloc] initWithCapacity:1];
    NSMutableArray *yearArray = [NSMutableArray array];
    for (int i=1; i<=3; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%d",(2011-3)+i]];
    }
    [pikcerDataSource  addObject:yearArray];
    
    NSMutableArray *monthArray = [NSMutableArray array];
    for (int i=1; i<=12; i++) {
        [monthArray addObject:[NSString stringWithFormat:@"%d",i]];
    }
    [pikcerDataSource addObject:monthArray];
       
    [startPickerView selectRow:[yearArray indexOfObject:[NSString stringWithFormat:@"%d",searchStartDate.year]] inComponent:0 animated:YES];
    [startPickerView selectRow:[monthArray indexOfObject:[NSString stringWithFormat:@"%d",searchStartDate.month]] inComponent:1 animated:YES];
    
    [endPickerView selectRow:[yearArray indexOfObject:[NSString stringWithFormat:@"%d",searchEndDate.year]] inComponent:0 animated:YES];
    [endPickerView selectRow:[monthArray indexOfObject:[NSString stringWithFormat:@"%d",searchEndDate.month]] inComponent:1 animated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewWillAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];
    
    [self statRecord];
    [self._tableView reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - * Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    NSString *title = nil;
	
	return title;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.dataSourceArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MonthReportViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    for (UIView *view in [cell.contentView subviews]) {
        [view removeFromSuperview];
    }
    
    [cell.contentView addSubview:[[self.dataSourceArray objectAtIndex:indexPath.row] objectForKey:kRowViewKey]];
    
    return cell;
}

//// Override to support conditional editing of the table view.
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    // Return NO if you do not want the specified item to be editable.
//    return YES;
//}
//
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleNone;
//}
//
//// Override to support editing the table view.
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        // Delete the row from the data source
//    }   
//    else if (editingStyle == UITableViewCellEditingStyleInsert) {
//        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
//    }   
//    
//}
//
//- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
//{
//	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
//}
//
//- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
//{
//	NSLog(@"section: %d, row: %d", indexPath.section, indexPath.row);
//}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - * Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - * UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSMutableArray *array= [pikcerDataSource objectAtIndex:component];
	if (pickerView.tag == 100)
	{
        if (component == 0) {
            searchStartDate.year = [[array objectAtIndex:row] intValue];
        }
        else {
            searchStartDate.month = [[array objectAtIndex:row] intValue];
        }
        
	}
    else if(pickerView.tag ==101) {
        if (component == 0) {
            searchEndDate.year = [[array objectAtIndex:row] intValue];
        }
        else {
            searchEndDate.month = [[array objectAtIndex:row] intValue];
        } 
    }
}

#pragma mark - * UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *content=@"";
    
    NSMutableArray *array= [pikcerDataSource objectAtIndex:component];
    content =[array objectAtIndex:row];
    
	return content;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 60.0;
	
	if (component == 0)
		componentWidth = 100.0;	// first column size is wider to hold names
	else
		componentWidth = 60.0;	// second column is narrower to show numbers
	
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSMutableArray *array= [pikcerDataSource objectAtIndex:component];
	return [array count]; 
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 2;
}

#pragma mark - * actions

-(void)chartAction {

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] 
                                 initWithTitle:@"返回" 
                                 style:UIBarButtonItemStyleBordered 
                                 target:nil 
                                 action:nil];
    
    ColumnChartViewController *controller = [[ColumnChartViewController alloc] init];
    self.navigationController.navigationItem.backBarButtonItem =backItem;
    
    NSMutableArray *dataArray = [NSMutableArray array];
    for (int i=0;i<[self.dataSourceArray count];i++) {
        MonthReportItem *item =[[self.dataSourceArray objectAtIndex:i] objectForKey:kRowItemKey];
        
        ColumnChartItem *chartItem = [[ColumnChartItem alloc] init];
        chartItem.title = [NSString stringWithFormat:@"%d/%02d",item.date.year,item.date.month];
        chartItem.firstValue = item.expenseValue;
        chartItem.secondValue = item.incomeValue;
        
        controller.incomeValue += item.incomeValue;
        controller.expenseValue += item.expenseValue;
        controller.totalValue += item.totalValue;
        
        [dataArray addObject:chartItem];
        [chartItem release];
    }
    controller.dataSourceArray = dataArray;
    [self.navigationController pushViewController:controller animated:YES];
    [backItem release];
}

-(void) statRecord {
    NSMutableArray *resultArray = [NSMutableArray array];
    NSMutableArray *monthArray = [NSMutableArray array];
    
    NSString *sql = @"select * from record a,record b";
    sql = [sql stringByAppendingFormat:@" where (a.year>=%d and a.month>=%d) and (b.year<=%d and b.month<=%d) and a.id=b.id ",
           searchStartDate.year,
           searchStartDate.month,
           searchEndDate.year,
           searchEndDate.month];
    
    NSMutableArray  *array = [g_Database getRecordArrayBySql:sql];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [array sortUsingDescriptors:sortDescriptors];
    [sortDescriptor release];
    
    for(RecordWrapper *record in array)
    {
        if ([resultArray count]==0) {
            MonthReportItem *newItem = [[MonthReportItem alloc] init];
            
            MyDate *date = [[MyDate alloc] init];
            date.year=record.year;
            date.month = record.month;
            
            newItem.date = date;
            newItem.dateString =[NSString stringWithFormat:@"%d%02d",record.year,record.month];
            [date release];
            
            if ([record.type isEqualToString:@"收入"]) {
                newItem.incomeValue = record.money;
                newItem.totalValue = newItem.incomeValue;
            }
            else {
                newItem.expenseValue = record.money;
                newItem.totalValue -= record.money;
            }
            
            [monthArray addObject:[NSString stringWithFormat:@"%d%02d",record.year,record.month]];
            [resultArray addObject:newItem];
            [newItem release];
        }
        else {
            MonthReportItem *item = [resultArray objectAtIndex:[resultArray count]-1];
            if (item.date.year == record.year && item.date.month == record.month) {
                if ([record.type isEqualToString:@"收入"]) {
                    item.incomeValue +=record.money;
                    item.totalValue += record.money;
                }
                else {
                    item.expenseValue += record.money;
                    item.totalValue -= record.money;
                }
            }
            else {
                MonthReportItem *newItem = [[MonthReportItem alloc] init];
                
                MyDate *date = [[MyDate alloc] init];
                date.year=record.year;
                date.month = record.month;
                
                newItem.date = date;
                newItem.dateString =[NSString stringWithFormat:@"%d%02d",record.year,record.month];
                [date release];
                
                if ([record.type isEqualToString:@"收入"]) {
                    newItem.incomeValue = record.money;
                    newItem.totalValue = newItem.incomeValue;
                }
                else {
                    newItem.expenseValue = record.money;
                    newItem.totalValue -= record.money;
                }
                
                [monthArray addObject:[NSString stringWithFormat:@"%d%02d",record.year,record.month]];
                [resultArray addObject:newItem];
                [newItem release];
             }
        }
    }
    
    int startYear=searchStartDate.year;
    int startMonth=searchStartDate.month;
    int endYear=searchEndDate.year;
    int endMonth =searchEndDate.month;
    if (startYear == endYear) {
        for (int i=startMonth; i<=endMonth; i++) {
            if (![monthArray containsObject:[NSString stringWithFormat:@"%d%02d",startYear,i]]) {
                MonthReportItem *newItem = [[MonthReportItem alloc] init];
                
                MyDate *date = [[MyDate alloc] init];
                date.year=startYear;
                date.month = i;
                
                NSLog(@"dateString=%@",[NSString stringWithFormat:@"%d%02d",startYear,i]);
                
                newItem.date = date;
                newItem.dateString =[NSString stringWithFormat:@"%d%02d",startYear,i];
                [date release];
                [resultArray addObject:newItem];
                [newItem release];
            }
        }
    }
    else {
        for (int i=startMonth; i<=12; i++) {
            if (![monthArray containsObject:[NSString stringWithFormat:@"%d%02d",startYear,i]]) {
                MonthReportItem *newItem = [[MonthReportItem alloc] init];
                
                MyDate *date = [[MyDate alloc] init];
                date.year=startYear;
                date.month = i;
                
                newItem.date = date;
                newItem.dateString =[NSString stringWithFormat:@"%d%02d",startYear,i];
                [date release];
                [resultArray addObject:newItem];
                [newItem release];
            }
        }
        
        startYear++;
        while (1) {
            if (startYear==endYear) {
                for (int i=1; i<=endMonth; i++) {
                    if (![monthArray containsObject:[NSString stringWithFormat:@"%d%02d",startYear,i]]) {
                        MonthReportItem *newItem = [[MonthReportItem alloc] init];
                        
                        MyDate *date = [[MyDate alloc] init];
                        date.year=startYear;
                        date.month = i;
                        
                        newItem.date = date;
                        newItem.dateString =[NSString stringWithFormat:@"%d%02d",startYear,i];
                        [date release];
                        [resultArray addObject:newItem];
                        [newItem release];
                    }
                }
                break;
            }
            else {
                for (int i=1; i<=12; i++) {
                    if (![monthArray containsObject:[NSString stringWithFormat:@"%d%02d",startYear,i]]) {
                        MonthReportItem *newItem = [[MonthReportItem alloc] init];
                        
                        MyDate *date = [[MyDate alloc] init];
                        date.year=startYear;
                        date.month = i;
                        
                        newItem.date = date;
                        newItem.dateString =[NSString stringWithFormat:@"%d%02d",startYear,i];
                        [date release];
                        [resultArray addObject:newItem];
                        [newItem release];
                    }
                }
                startYear++;
            } 
        }
    }
    
    NSSortDescriptor *endSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateString" ascending:YES];
    NSArray *endSortDescriptors = [NSArray arrayWithObject:endSortDescriptor];
    [resultArray sortUsingDescriptors:endSortDescriptors];
    [endSortDescriptor release];
    
    CGRect appRect =[[UIScreen mainScreen] applicationFrame];
    [self.dataSourceArray removeAllObjects];
    for (MonthReportItem *item in resultArray) {
        [self.dataSourceArray addObject:
         [NSDictionary dictionaryWithObjectsAndKeys:
          item,kRowItemKey,
          [self tableCellView:item frame:CGRectMake(0, 0, appRect.size.width, 50)],kRowViewKey,
          nil]];
    }
}

-(id)tableCellView:(MonthReportItem *)item frame:(CGRect)frame 
{
    UIView *view = [[[UIView alloc] initWithFrame:frame] autorelease];
    
    UILabel *monthLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 80, 42)];
    monthLable.textColor = [UIColor darkTextColor];
    monthLable.font = [UIFont systemFontOfSize:16];
    monthLable.text = [NSString stringWithFormat:@"%d/%02d",item.date.year,item.date.month];
    [view addSubview:monthLable];
    [monthLable release];
    
    UILabel *incomeLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 4, 100, 20)];
    incomeLable.textColor = [UIColor blueColor];
    incomeLable.font = [UIFont systemFontOfSize:12];
    incomeLable.text = [NSString stringWithFormat:@"%.2f",item.incomeValue];
    [view addSubview:incomeLable];
    [incomeLable release];
    
    UILabel *expenseLable = [[UILabel alloc] initWithFrame:CGRectMake(100, 24, 100, 20)];
    expenseLable.textColor = [UIColor purpleColor];
    expenseLable.font = [UIFont systemFontOfSize:12];
    expenseLable.text = [NSString stringWithFormat:@"%.2f",item.expenseValue];
    [view addSubview:expenseLable];
    [expenseLable release];
    
    UILabel *totalLable = [[UILabel alloc] initWithFrame:CGRectMake(200, 4, 100, 42)];
    totalLable.font = [UIFont systemFontOfSize:16];
    totalLable.text = [NSString stringWithFormat:@"%.2f",item.totalValue];
    [view addSubview:totalLable];
    [totalLable release];
    
    return view;
}

-(void)titleAction {
    
    if (dateSelectView.isHidden) {
        [titleButton setImage:[UIImage imageNamed:@"group_button_up.png"] forState:UIControlStateNormal];
        CGRect appRect = [[UIScreen mainScreen] applicationFrame];
        [UIView beginAnimations:nil context:nil];
        dateSelectView.frame =CGRectMake(0, appRect.size.height -250-44, appRect.size.width, 250);
        dateSelectView.hidden=NO;
        [UIView commitAnimations];   
    }
    else {
        [titleButton setImage:[UIImage imageNamed:@"group_button_down.png"] forState:UIControlStateNormal];
        CGRect appRect = [[UIScreen mainScreen] applicationFrame];
        [UIView setAnimationDuration:2];
        [UIView beginAnimations:nil context:nil];
        dateSelectView.frame = CGRectMake(0, appRect.size.height, appRect.size.width, 250);
        dateSelectView.hidden=YES;
        [UIView commitAnimations]; 
    }
}

-(IBAction)cancelAction
{
    [titleButton setImage:[UIImage imageNamed:@"group_button_down.png"] forState:UIControlStateNormal];
    CGRect appRect = [[UIScreen mainScreen] applicationFrame];
    [UIView setAnimationDuration:2];
    [UIView beginAnimations:nil context:nil];
    dateSelectView.frame = CGRectMake(0, appRect.size.height, appRect.size.width, 250);
    dateSelectView.hidden=YES;
    [UIView commitAnimations]; 
}

-(IBAction)doneAction
{
    [titleButton setImage:[UIImage imageNamed:@"group_button_down.png"] forState:UIControlStateNormal];
    CGRect appRect = [[UIScreen mainScreen] applicationFrame];
    [UIView setAnimationDuration:2];
    [UIView beginAnimations:nil context:nil];
    dateSelectView.frame = CGRectMake(0, appRect.size.height, appRect.size.width, 250);
    dateSelectView.hidden=YES;
    [UIView commitAnimations]; 
    
    NSMutableArray *startYearArray= [pikcerDataSource objectAtIndex:0];
    searchStartDate.year = [[startYearArray objectAtIndex:[startPickerView selectedRowInComponent:0]] intValue];
    NSMutableArray *startMonthArray= [pikcerDataSource objectAtIndex:1];
    searchStartDate.month = [[startMonthArray objectAtIndex:[startPickerView selectedRowInComponent:1]] intValue];
    
    NSMutableArray *endYearArray= [pikcerDataSource objectAtIndex:0];
    searchEndDate.year = [[endYearArray objectAtIndex:[endPickerView selectedRowInComponent:0]] intValue];
    NSMutableArray *endMonthArray= [pikcerDataSource objectAtIndex:1];
    searchEndDate.month = [[endMonthArray objectAtIndex:[endPickerView selectedRowInComponent:1]] intValue]; 
    
    NSString *titleString =[NSString stringWithFormat:@" %04d/%02d-%04d/%02d",searchStartDate.year,searchStartDate.month,searchEndDate.year,searchEndDate.month];
    [titleButton setTitle:titleString forState:UIControlStateNormal];
    [self statRecord];
    [self._tableView reloadData];
}

@end
